package controller.common;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import pojos.common.ReplyMessage;
import pojos.common.SmsAuthCode;
import service.SmsNotifyService;
import utils.InputVerifyUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * 手机号验证控制器
 */
@Controller
public class PhoneVerifyController {

    @Resource(name="sendSmsService")
    private SmsNotifyService smsNotifyService;

    /**
     * 修改手机号
     */
    @PostMapping("/utils/smsCodeForChangePhone")
    @ResponseBody
    public ReplyMessage changePhoneNum(String phone, String imgCode, HttpServletRequest request){
        HttpSession session = request.getSession();

        ReplyMessage replyMessage = new ReplyMessage();

        if(InputVerifyUtils.isImgAuthCodeNotRight(session,imgCode)){
            replyMessage.setStatus(400);
            replyMessage.setInfo("图片验证码不正确！");
            return replyMessage;
        }

        if(InputVerifyUtils.isPhoneNotRight(phone)){
            replyMessage.setStatus(400);
            replyMessage.setInfo("手机号不正确！");
            return replyMessage;
        }

        replyMessage = smsNotifyService.phoneNumVerify(phone,2);
        if(replyMessage.getStatus() == 200){
            // 验证码存入Session
            SmsAuthCode smsAuthCode = new SmsAuthCode();
            smsAuthCode.setAuthCode(replyMessage.getInfo());
            smsAuthCode.setGenerateTime(System.currentTimeMillis());
            session.setAttribute("SmsAuthCode",smsAuthCode);

            replyMessage.setInfo("");
        }
        return replyMessage;
    }

    /**
     * 忘记密码
     */
    @PostMapping("/utils/smsForForgetPassword")
    @ResponseBody
    public ReplyMessage forgetPassword(String phoneNum,String imgCode,HttpServletRequest request){
        ReplyMessage replyMessage = new ReplyMessage();
        HttpSession session = request.getSession();

        if(InputVerifyUtils.isImgAuthCodeNotRight(session,imgCode)){
            replyMessage.setStatus(400);
            replyMessage.setInfo("图片验证码不正确！");
            return replyMessage;
        }

        if(InputVerifyUtils.isPhoneNotRight(phoneNum)){
            replyMessage.setStatus(400);
            replyMessage.setInfo("手机号不正确！");
            return replyMessage;
        }

        replyMessage = smsNotifyService.phoneNumVerify(phoneNum,1);
        if(replyMessage.getStatus() == 200){
            // 验证码存入Session
            SmsAuthCode smsAuthCode = new SmsAuthCode();
            smsAuthCode.setAuthCode(replyMessage.getInfo());
            smsAuthCode.setGenerateTime(System.currentTimeMillis());
            session.setAttribute("SmsAuthCode",smsAuthCode);

            replyMessage.setInfo("");
        }
        return replyMessage;
    }
}
